package com.example.demoratelimit.aspect.limit;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope
@Aspect
@Slf4j
public class LimitAspect {
	//每秒只发出指定个令牌(这里方便测试用1个)，此处是单进程服务的限流,内部采用令牌捅算法实现
	private static RateLimiter rateLimiter = RateLimiter.create(1.0);

	//Controller层切点  限流
	@Pointcut("@annotation(com.example.demoratelimit.aspect.limit.RequestLimit)")
	public void requestAspect() {
		
	}
    @Around("requestAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) throws Throwable {

    	Boolean flag = rateLimiter.tryAcquire();
    	Object obj = null;
		if(flag){
			obj = joinPoint.proceed();
		}else {
			log.info("哎哟喂，业务太火爆，稍等一会儿呗");
			throw new Exception("哎哟喂，业务太火爆，稍等一会儿呗");
		}
    	return obj;
    } 
}
